/**
 * Created by Administrator on 2017/5/25 0025.
 */
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');

var DB = require('../../model/db');
var sd = require('silly-datetime');
var session = require("express-session");  /*引入session*/

//设置session中间件
router.use(session({
    secret: 'keyboard cat',  /*加密方式*/
    resave: false,
    saveUninitialized: true
}));

var md5 = require('md5-node');  //md5 模块
//md5('hello world');

router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: false }));

var Host = '';
router.use(function(req, res,next){
    Host="http://"+req.headers.host;
    next();
})


/* GET users listing. */
router.get('/', function(req, res, next) {
    //res.send('login');
    //console.log(DB)
    res.render('admin/login',{
        host:Host
    })
});



//后台入口

router.post('/doLogin', function(req, res, next) {
    // res.send('user add');
    // console.log(req.body);
    var username = req.body.username;
    var password = md5(req.body.password);
    var logintime = sd.format(new Date(), 'YYYY-MM-DD HH:mm');

    DB.find('admin',{"username":username,"password":password},function(err,data){

        if(err){
            console.log(err);
            return;
        }
        if(data.length>0){//登录成功
            session.userinfo=data[0];  /*所有的用户信息放在了 userInfo*/
            res.redirect(Host+'/admin/index');  /*登录成功跳转到首页*/

            DB.updateOne('admin',{_id:new DB.ObjectID(data[0]._id)},{last_login_time:logintime},function(err,result){
                if(err){
                    console.log(err);
                    return
                }
            })

        }else{//登录失败

            res.send("<script>alert('用户名或者密码错误');location.href='/admin/login'</script>");
        }

    })
});


module.exports = router;

